package com.until;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Properties;
import java.util.UUID;

public class OSSUtil {
    private static Properties properties=new Properties();
    static {
        InputStream is=OSSUtil.class.getResourceAsStream("/project.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String uploadFile(String pathFile, MultipartFile multipartFile){
        InputStream inputStream=null;
        OSS ossClient=null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilName = UUID.randomUUID() + suffix;
            inputStream=multipartFile.getInputStream();
            ossClient=new OSSClientBuilder().build(properties.getProperty("oss.endpoint"),
                    properties.getProperty("oss.accessKeyId"),
                    properties.getProperty("oss.accessKeySecret"));
            ossClient.putObject(properties.getProperty("oss.bucketName"),pathFile+"/"+newFilName,inputStream);
            return properties.getProperty("oss.url")+pathFile+"/"+newFilName;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(ossClient!=null){
                ossClient.shutdown();
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public static void downloadFile(String filePath, HttpServletResponse response){
        OSS ossClient=null;
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        filePath=filePath.replace(properties.getProperty("oss.url"),"");
        String fileName=filePath.substring(filePath.lastIndexOf("/")+1);
        try {
            // 创建OSSClient实例。
            ossClient=new OSSClientBuilder().build(properties.getProperty("oss.endpoint"),
                    properties.getProperty("oss.accessKeyId"),
                    properties.getProperty("oss.accessKeySecret"));
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject=ossClient.getObject(properties.getProperty("oss.bucketName"),filePath);
            //得到要下载对象得输入流
            //设置下载文件的头部信息     attachment  附件
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            //字节输出流  下载的本质把服务上的文件对象变成输入流（内存）   然后把输入流的内容输出到相应对象HttpServletResponse的输出流中
            //套接缓存流，让下载文件速度提高
            bis =new BufferedInputStream(ossObject.getObjectContent());
            bos =new BufferedOutputStream( response.getOutputStream());
            //定义缓存字节数组
            byte[]  bytes = new byte[2048];
            //定义每次读取字节数
            int readNum = -1;
            //循环读写
            while((readNum=bis.read(bytes))!=-1){
                //System.out.println(readNum+".............................");
                //写入Response输出流
                bos.write(bytes,0,readNum);
            }
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
            try {
                if(bos!=null){
                    bos.close();
                }
                if(bis!=null){
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
